import store from '@/store';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import history from './history';
import { clearToken, getToken } from './storage';
import { setToken } from './storage';
import { LocationStateType } from '@/components/AuthRoute';

export const baseURL = 'http://geek.itheima.net';

const http = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

http.interceptors.request.use(
  function (config) {
    const { token } = getToken();
    if (config.headers && token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    console.dir(error);
    if (!error.response) {
      Toast.show({ content: '网络开小差了，请检查网络' });
      return Promise.reject(error);
    }
    if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.message });
    } else {
      const refresh_token = getToken().refresh_token;
      if (refresh_token) {
        try {
          const res = await axios({
            url: baseURL + '/v1_0/authorizations',
            method: 'put',
            headers: {
              Authorization: `Bearer ${refresh_token}`,
              'Content-Type': 'application/x-www-form-urlencoded',
            },
          });
          console.log('res.data.token  ----->  ', res.data.data.token);
          const auth = { token: res.data.data.token, refresh_token };
          store.dispatch({
            type: 'user/saveAuth',
            payload: auth,
          });
          setToken(auth);
          return http(error.config);
        } catch (error) {
          clearToken();
          store.dispatch({
            type: 'user/saveAuth',
            payload: {} as any,
          });
          history.push('/login', {
            from: history.location.pathname,
          } as LocationStateType);
        }
      } else {
        history.push('/login', {
          from: history.location.pathname,
        } as LocationStateType);
      }

      Toast.show({ content: '登录超时，请重新登录' });
    }

    return Promise.reject(error);
  }
);

export default http;
